#!/usr/bin/env bash


# 检查是否已安装docker
docker -v

! test -d conf &&  echo "请切换到 mysql-slave 目录"  &&   exit 1


echo  -e "\033[31m请确认本机 13306,13307 端口没有占用,否则启动MySQL失败  \033[0m"


test -d data && rm -rf data

chmod +x docker-compose

echo -e "\033[31m拉取MySQL镜像 \033[0m"
./docker-compose -f docker-compose.yml up -d

echo -e "\033[31m正在启动MySQL \033[0m"

# 等待MySQL初始化
sleep 10

# 登录MySQL主从命令
MASTERCMD="mysql -u root -h 127.0.0.1 -P13306 -p123456 "
SLAVECMD=" mysql -u root -h127.0.0.1  -P13307 -p123456"

echo -e "\033[31m主库操作授权操作 \033[0m"
# 主库操作授权操作
echo "GRANT REPLICATION SLAVE ON *.* TO 'slave'@'%' IDENTIFIED BY 'slave';"  | $MASTERCMD
echo "flush privileges;"  | $MASTERCMD
echo "create database fileserver default character set utf8mb4;"  | $MASTERCMD

# 获取binlong文件 Position
BINLOGFILE=$(echo "show master status \G;" | $MASTERCMD | grep -E -o "log.[0-9]+")
BINLOGPOS=$(echo "show master status \G;" | $MASTERCMD  | grep Position |grep  -E -o "[0-9]+")

sleep 3
# 从库
echo -e "\033[31m从库操作 \033[0m"
echo "stop slave;" |  $SLAVECMD
echo "create database fileserver default character set utf8mb4;" |  $SLAVECMD
echo CHANGE MASTER TO MASTER_HOST="'master.mysql.com'",master_port=3306,MASTER_USER="'slave'",MASTER_PASSWORD="'slave'",MASTER_LOG_FILE="'${BINLOGFILE}'",MASTER_LOG_POS="${BINLOGPOS}" ";" |  $SLAVECMD
echo " start slave;" |  $SLAVECMD
echo "show slave status \G;" |  $SLAVECMD | grep Yes &&  echo -e "\033[32m主从搭建成功\033[0m"

echo -e "\033[31m登录主库的地址为 127.0.0.1:13306 或  主机ip:13306 密码 123456 \033[0m"
echo -e "\033[32m登录从库的地址为 127.0.0.1:13307 或  主机ip:13307 密码 123456 \033[0m"


